<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/3
 * Time: 16:12
 */

namespace app\mtsuperadmin\controller;

use app\command\controller\Generate;
use app\util\Strs;
use think\facade\Validate;
use app\mtadminapi\model\MtAdminSysAccount;
use app\command\controller\Common;
use app\mtadminapi\controller\Base;
use app\util\ReturnCode;

/**
 * 管理员管理
 * Class AdminSysUser
 * @package app\mtadminapi\controller
 */
class AdminSysUserAdmin extends Base
{
    /**
     * 管理员添加
     * @return mixed json
     */
    public function adminUserAdd(){
        $userName = $this->request->post("userName");
        $passWord = $this->request->post("passWord");
        $shopID = $this->request->post("shopID")?intval($this->request->post("shopID")):"";
        $adminNick = $this->request->post("adminNick");
        $addAdminID = $this->request->param("adminID");
        /**
         * @todo 文件上传
         */
        $rule = [
            'userName'   => 'require|max:10',
            'passWord' => 'require',
        ];
        $msg = [
            'userName.require' => 'userName不能为空',
            'userName.max'   => 'userName最长10位',
            'passWord.require'   =>  'passWord不能为空',
        ];
        $data = [
            "userName" => $userName,
            "passWord" => (new Generate())->passwordHash($passWord),
            "shopID"   => !empty($shopID) ? $shopID : "",
            "adminNick" => isset($adminNick) ? $adminNick : Strs::randString(6,4),
            'cTime'     =>time(),
            "addAdminID"    => $addAdminID,
        ];
        $validate = Validate::make($rule)->message($msg);
        $result = $validate->check($data);
        if(!$result){
            return $this->error(ReturnCode::PARAM_INVALID,$validate->getError());
        }
        $res = (new MtAdminSysAccount())->insert($data,true);
        if ($res === 2) {
            return $this->error(ReturnCode::ADD_REPEAT, "重复数据");
        } elseif ($res === 1) {
            return $this->success("添加成功");
        }
        return $this->error(ReturnCode::ADD_FAILED, "添加失败");
    }

    /**
     * 管理员修改管理员信息
     * @return array
     */
    public function adminUserUpdate(){
        $data = $this->request->post();
        $updateAdminID = $this->request->param("adminID");
        $obj = new MtAdminSysAccount();
        if($data['adminID']){
            $data['mTime'] = time();
            $data['updateAdminID'] = $updateAdminID;
            $res = $obj->update($data,["adminID"=>$data['adminID']]);
            if(!$res){
                return $this->bindError(ReturnCode::DB_SAVE_ERROR,"修改失败");
            }
            return $this->bindSuccess("修改成功");
        }
    }
}